import {Student} from '../types/student'
import { getFormattedCurrentDateTime, validateEmail, validatePhone } from "@utils/helpers";
//类的方法
class StudentManager { 
    private students: Student[] = []
    private keyworlds: string = ''
    constructor() {
        this.loadStudentsFromLocalStorage()///本地存储数据
        this.renderTable()//渲染的方法，加载本地数据
        this.bindEvents();//增加的方法
    }
    //本地存储数据
    loadStudentsFromLocalStorage() {
        const data = localStorage.getItem('students')
        if (data) {
            this.students = JSON.parse(data)
        } else {

            this.students = [
                {
                    id: 1,
                    name: 'Alice',
                    gender: 'Female',
                    hobbies: 'Reading',
                    email: 'alice@example.com',
                    phone: '12345678901',
                    age: 20,
                    create_at: getFormattedCurrentDateTime(),
                    update_at: getFormattedCurrentDateTime(),
                },
                {
                    id: 2,
                    name: 'Bob',
                    gender: 'Male',
                    hobbies: 'Sports',
                    email: 'bob@example.com',
                    phone: '10987654321',
                    age: 22,
                    create_at: getFormattedCurrentDateTime(),
                    update_at: getFormattedCurrentDateTime(),
                },
            ];
        }
    }
    // 保存学生数据到本地存储
    saveStudentsToLocalStorage() {
        localStorage.setItem('students', JSON.stringify(this.students))
    }
    //渲染的方法，加载本地数据
    renderTable() {
        const tbody = document.querySelector(".studentTable tbody") as HTMLElement
        tbody.innerHTML = ''
        const filteredStudents = this.keyworlds ? this.students.filter((student) => {
           return student.name.toLowerCase().includes(this.keyworlds.toLowerCase())
        }) : this.students;
        console.log(filteredStudents)
        filteredStudents.forEach((student) => {
            const row = document.createElement('tr')
            row.innerHTML = `
                            <td><input type="checkbox"  class="selectStudent" data-id="${student.id}"></td>
                            <td>${student.id}</td>
                            <td>${student.name}</td>
                            <td>${student.gender}</td>
                            <td>${student.hobbies}</td>
                            <td>${student.email}</td>
                            <td>${student.phone}</td>
                            <td>${student.age}</td>
                            <td>${student.create_at}</td>
                            <td>${student.update_at}</td>
                            <td>
                                <button class="editBtn" data-id="${student.id}">Edit</button>
                                <button class="deleteBtn" data-id="${student.id}">Delete</button>
                            </td>
                            `
            tbody.appendChild(row)
        })

    }
    //增加的方法
    bindEvents() {
        //添加按钮的获取,添加学生按钮
        const openModalBtn = document.querySelector('.openModalBtn') as HTMLButtonElement;
        openModalBtn.addEventListener('click', this.openAddModal)
        //全选复选框
        const selectAllCheckbox = document.querySelector('.selectAll') as HTMLInputElement;
        selectAllCheckbox.addEventListener('change', (e) => this.selectAllStudents(e))
        //表单提交
        const studentForm = document.querySelector('.studentForm') as HTMLFormElement;
        studentForm.addEventListener('submit', (e) => this.handleFormSubmit(e))
        // 表格中的编辑和删除按钮
        const tbody = document.querySelector('.studentTable tbody') as HTMLElement;
        tbody.addEventListener('click', (e) => this.handleTableActions(e))
        //实现搜索功能
        const searchBtn = document.querySelector('.searchBtn') as HTMLButtonElement;
        searchBtn.addEventListener('click', () => this.searchStudents());
        //模糊框关闭事件
        window.addEventListener('click', (e) => this.closeModal(e))
    }
    // 打开添加学生的模态框
    openAddModal() {
        const modal = document.querySelector('.studentModal') as HTMLElement;
        const modalTitle = document.querySelector('.modalTitle') as HTMLElement;
        const studentForm = document.querySelector('.studentForm') as HTMLFormElement;
        modalTitle.textContent = 'Add New Student';
        (studentForm.querySelector('.studentIdToEdit') as HTMLInputElement).value = '';
        modal.style.display = 'block'
    }
    //关闭模糊框
    closeModal(e: Event) {
        const modal = document.querySelector('.studentModal') as HTMLElement;
        if (e.target === modal) {
            console.log(e.target)
            modal.style.display = 'none'
        }
    }
    //表单提交处理
    handleFormSubmit(e: Event) {
        e.preventDefault()
        const studentForm = e.target as HTMLFormElement;
        //获取添加弹窗里面的value值
        const id = (studentForm.querySelector('.studentIdToEdit') as HTMLInputElement).value;
        const name = (studentForm.querySelector('.studentName') as HTMLInputElement).value.trim();
        const gender = (studentForm.querySelector('.studentGender') as HTMLSelectElement).value;
        const hobbies = (studentForm.querySelector('.studentHobbies') as HTMLInputElement).value.trim();
        const email = (studentForm.querySelector('.studentEmail') as HTMLInputElement).value.trim();
        const phone = (studentForm.querySelector('.studentPhone') as HTMLInputElement).value.trim();
        const age = parseInt((studentForm.querySelector('.studentAge') as HTMLInputElement).value, 10);
        //验证输入
        if (!name || !gender || !hobbies || !email || !phone || !age) {
            alert('Please fill in all fields.');
            return
        }
        if (!validateEmail(email)) {
            alert('Invalid email format.');
            return;
        }
        if (!validatePhone(phone)) {
            alert('Invalid phone number format.');
            return;
        }
        if (id) {
            //编辑学生
            const student = this.students.find((s) => s.id === parseInt(id, 10))
            if (student) {
                student.name = name;
                student.gender = gender;
                student.hobbies = hobbies;
                student.email = email;
                student.phone = phone;
                student.age = age;
                student.update_at = getFormattedCurrentDateTime();
            }
        } else {
            //添加新学生
            const newstudent: Student = {
                id: this.students.length ? this.students[this.students.length - 1].id + 1 : 1,
                name,
                gender,
                hobbies,
                email,
                phone,
                age,
                create_at: getFormattedCurrentDateTime(),
                update_at: getFormattedCurrentDateTime()
            }
            this.students.push(newstudent);
        }
        this.saveStudentsToLocalStorage()
        this.renderTable()
        const modal = document.querySelector('.studentModal') as HTMLElement;
        modal.style.display = 'none';
    }
    //处理表格中的编辑和删除操作
    handleTableActions(e: Event) {
        const target = e.target as HTMLElement;
        const id = parseInt(target.getAttribute('data-id') || '0', 10);
        if (target.classList.contains('deleteBtn')) {
            this.deleteStudent(id)
        }else if(target.classList.contains('editBtn')){
            this.openEditModal(id)
        }
    }
    deleteStudent(id: number) {
        if (confirm('Are you sure you want to delete this student?')) {
            this.students = this.students.filter((s) => s.id !== id)//s.id !== id：这是一个比较操作，如果元素s的id属性不等于变量id的值，则表达式返回true，该元素会被包含在返回的新数组中
            this.saveStudentsToLocalStorage();
            this.renderTable();
        }
    }
    // 打开编辑学生的模态框
    openEditModal(id:number){
        const student = this.students.find((s) => s.id === id);
        if (!student) return;
        const modal = document.querySelector('.studentModal') as HTMLElement;
        const modalTitle = document.querySelector('.modalTitle') as HTMLElement;
        const studentForm = document.querySelector('.studentForm') as HTMLFormElement;
        modalTitle.textContent = 'Edit Student';
        (studentForm.querySelector('.studentIdToEdit') as HTMLInputElement).value = student.id.toString();
        (studentForm.querySelector('.studentName') as HTMLInputElement).value = student.name;
        (studentForm.querySelector('.studentGender') as HTMLSelectElement).value = student.gender;
        (studentForm.querySelector('.studentHobbies') as HTMLInputElement).value = student.hobbies;
        (studentForm.querySelector('.studentEmail') as HTMLInputElement).value = student.email;
        (studentForm.querySelector('.studentPhone') as HTMLInputElement).value = student.phone;
        (studentForm.querySelector('.studentAge') as HTMLInputElement).value = student.age.toString();
        modal.style.display = 'block';
    }
    //搜索功能
    searchStudents(){
        const keywordInput = document.querySelector('.keyword') as HTMLInputElement;
        this.keyworlds = keywordInput.value.trim();
        console.log(this.keyworlds);
        this.renderTable();
    }
    //全选/取消全选学生
    selectAllStudents(e: Event) {
        const checked = (e.target as HTMLInputElement).checked //.checked 属性是一个布尔值，用于表示复选框（checkbox）或单选按钮（radio button）是否被选中。如果元素被选中，.checked 返回 true；如果未被选中，返回 false。
        const checkboxes = document.querySelectorAll('.selectStudent') as NodeListOf<HTMLInputElement>;
        checkboxes.forEach((checkbox) => (checkbox.checked = checked))
    }
}
//页面监听
document.addEventListener('DOMContentLoaded', () => {
    new StudentManager()
})